package com.luca.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luca.common.constant.UserConstants;
import com.luca.common.core.domain.JsonResult;
import com.luca.common.core.domain.entity.SysDictData;
import com.luca.common.core.domain.entity.SysDictType;
import com.luca.common.exception.BaseException;
import com.luca.common.exception.CustomException;
import com.luca.common.utils.DictUtils;
import com.luca.common.utils.StringUtils;
import com.luca.system.mapper.SysDictDataMapper;
import com.luca.system.mapper.SysDictTypeMapper;
import com.luca.system.service.ISysDictTypeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * 字典 业务层处理
 *
 * @author luca
 */
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements ISysDictTypeService {

    @Resource
    private SysDictDataMapper dictDataMapper;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PreDestroy
    public void init() {
        List<SysDictType> dictTypeList = baseMapper.selectList(null);
        for (SysDictType dictType : dictTypeList) {
            List<SysDictData> dictDatas = dictDataMapper.selectList(new QueryWrapper<SysDictData>().eq("status", 0).eq("dict_type", dictType).orderByAsc("dict_sort"));
            DictUtils.setDictCache(dictType.getDictType(), dictDatas);
        }
    }

    /**
     * 根据条件分页查询字典类型
     *
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeList(SysDictType dictType) {
        var query = new QueryWrapper<SysDictType>();
        if (StringUtils.isNotEmpty(dictType.getDictName())) {
            query.like("dict_name", dictType.getDictName());
        }
        if (!ObjectUtils.isEmpty(dictType.getStatus())) {
            query.eq("status", dictType.getStatus());
        }
        if (StringUtils.isNotEmpty(dictType.getDictType())) {
            query.like("dict_type", dictType.getDictType());
        }
        if (!ObjectUtils.isEmpty(dictType.getParams().get("beginTime"))) {
            query.ge("create_time", dictType.getParams().get("beginTime"));
        }
        if (!ObjectUtils.isEmpty(dictType.getParams().get("endTime"))) {
            query.le("create_time", dictType.getParams().get("endTime"));
        }
        return baseMapper.selectList(query);
    }

    /**
     * 根据所有字典类型
     *
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeAll() {
        return baseMapper.selectList(null);
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType) {
        List<SysDictData> dictDatas = DictUtils.getDictCache(dictType);
        if (StringUtils.isNotEmpty(dictDatas)) {
            return dictDatas;
        }
        dictDatas = dictDataMapper.selectList(new QueryWrapper<SysDictData>().eq("status", 0).eq("dict_type", dictType).orderByAsc("dict_sort"));
        if (StringUtils.isNotEmpty(dictDatas)) {
            DictUtils.setDictCache(dictType, dictDatas);
            return dictDatas;
        }
        return null;
    }

    /**
     * 根据字典类型ID查询信息
     *
     * @param dictId 字典类型ID
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeById(Long dictId) {
        return baseMapper.selectById(dictId);
    }

    /**
     * 根据字典类型查询信息
     *
     * @param dictType 字典类型
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeByType(String dictType) {
        return baseMapper.selectOne(new QueryWrapper<SysDictType>().eq("dict_type", dictType));
    }

    /**
     * 批量删除字典类型信息
     *
     * @param dictIds 需要删除的字典ID
     * @return 结果
     */
    @Override
    public int deleteDictTypeByIds(Long[] dictIds) {
        for (Long dictId : dictIds) {
            SysDictType dictType = baseMapper.selectById(dictId);
            if (dictDataMapper.selectCount(new QueryWrapper<SysDictData>().eq("dict_type", dictType.getDictType())) > 0) {
                throw new CustomException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
        }
        int count = baseMapper.deleteBatchIds(Arrays.asList(dictIds));
        if (count > 0) {
            DictUtils.clearDictCache();
        }
        return count;
    }

    /**
     * 清空缓存数据
     */
    @Override
    public void clearCache() {
        DictUtils.clearDictCache();
    }

    /**
     * 新增保存字典类型信息
     *
     * @param dictType 字典类型信息
     * @return 结果
     */
    @Override
    public int insertDictType(SysDictType dictType) {
        if (UserConstants.NOT_UNIQUE.equals(checkDictTypeUnique(dictType))) {
            throw new BaseException("新增字典'" + dictType.getDictName() + "'失败，字典类型已存在");
        }
        int row = baseMapper.insert(dictType);
        if (row > 0) {
            DictUtils.clearDictCache();
        }
        return row;
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dictType 字典类型信息
     * @return 结果
     */
    @Override
    public int updateDictType(SysDictType dictType) {
        if (UserConstants.NOT_UNIQUE.equals(checkDictTypeUnique(dictType))) {
            throw new BaseException("修改字典'" + dictType.getDictName() + "'失败，字典类型已存在");
        }
        SysDictType oldDict = baseMapper.selectById(dictType);
        oldDict.setDictName(dictType.getDictName());
        oldDict.setDictType(dictType.getDictType());
        oldDict.setStatus(dictType.getStatus());
        oldDict.setRemark(dictType.getRemark());
        int row = baseMapper.updateById(oldDict);
        if (row > 0) {
            DictUtils.clearDictCache();
        }
        return row;
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public String checkDictTypeUnique(SysDictType dict) {
        Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId();
        SysDictType dictType = baseMapper.selectOne(new QueryWrapper<SysDictType>().eq("dict_type", dict.getDictType()));
        if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}
